package com.ymatou.iapi.liveinfo.testcase;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.liveinfo.parameter.GetActivityInfoBean;
import com.ymatou.iapi.liveinfo.service.GetActivityInfoCall;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.*;
import com.ymt.utils.tag.*;
import com.ymttest.business.service.LiveCallService;
import com.ymttest.database.mongo.jproduct.LiveProductsWapper;
import com.ymttest.database.mongo.jproduct.LivesWapper;
import com.ymttest.database.mongo.jproduct.ProductsWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;
/**
*获取直播详情
*FreeMaker Template自动生成代码
*/
@TestSuite
public class Ts_GetActivityInfo{
	private static int sellerId = Integer.parseInt(EnvSetup.getData("productsellerid"));
	private static String sellerName = EnvSetup.getData("productsellername");
	private static GetActivityInfoBean bean;
	private static GetActivityInfoCall call;
	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("获取直播详情");
	}

	@Before
	public void caseUp() {
		bean=new GetActivityInfoBean();
		call=new GetActivityInfoCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(call.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_GetActivityInfo_001() {
		Logger.start(true,"获取直播详情-不带商品-状态是正在直播中");
		try {
			LivesWapper wapper = new LivesWapper();
		    Integer lid=LiveCallService.createLiveInProgress(sellerName,sellerId).getJSONObject("Data").getInt("ActivityId");
		    String cover="http://m.ymatou.com/"+TestDataManager.getRandomUUID().toString();
			wapper.updateCover(lid.toString(), cover);
			LiveCallService.CreateLivesProductByLivesId(sellerId,sellerName,lid);
			Thread.sleep(1000); 
			bean.setActivityId(lid);
			bean.setIncludeProducts(false);
			call.setData(bean);
			call.callService();	
			GetVerify(bean.getActivityId(),bean.getIncludeProducts());
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P2.class})
	@TestCase
	public void Tc_GetActivityInfo_002() {
		Logger.start(true,"获取直播详情-不带商品-状态是即将开始");
		try {
			int lid=LiveCallService.createLiveBeginInFuture(sellerName,sellerId).getJSONObject("Data").getInt("ActivityId");
			LiveCallService.CreateLivesProductByLivesId(sellerId,sellerName,lid);
			Thread.sleep(1000); 
			bean.setActivityId(lid);
			bean.setIncludeProducts(false);
			call.setData(bean);
			call.callService();	
			GetVerify(bean.getActivityId(),bean.getIncludeProducts());	
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P2.class})
	@TestCase
	public void Tc_GetActivityInfo_003() {
		Logger.start(true,"获取直播详情-不带商品-状态是未生效");
		try {
			int lid=LiveCallService.createLiveNotInEffect(sellerName,sellerId).getJSONObject("Data").getInt("ActivityId");
			LiveCallService.CreateLivesProductByLivesId(sellerId,sellerName,lid);
			Thread.sleep(1000); 
			bean.setActivityId(lid);
			bean.setIncludeProducts(false);
			call.setData(bean);
			call.callService();	
			GetVerify(bean.getActivityId(),bean.getIncludeProducts());	
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P3.class})
	@TestCase
	public void Tc_GetActivityInfo_004() {
		Logger.start(false,"获取直播详情-带商品-状态是正在直播中");
		try {
		    int lid=LiveCallService.createLiveInProgress(sellerName,sellerId).getJSONObject("Data").getInt("ActivityId");
			LiveCallService.CreateLivesProductByLivesId(sellerId,sellerName,lid);
			Thread.sleep(1000); 
			bean.setActivityId(lid);
			bean.setIncludeProducts(true);
			call.setData(bean);
			call.callService();	
			GetVerify(bean.getActivityId(),bean.getIncludeProducts());		
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P3.class})
	@TestCase
	public void Tc_GetActivityInfo_005() {
		Logger.start(false,"获取直播详情-带商品-状态是即将开始");
		try {
			int lid=LiveCallService.createLiveBeginInFuture(sellerName,sellerId).getJSONObject("Data").getInt("ActivityId");
			LiveCallService.CreateLivesProductByLivesId(sellerId,sellerName,lid);
			//bean.setActivityId(159209);
			bean.setActivityId(lid);
			bean.setIncludeProducts(true);
			call.setData(bean);
			call.callService();	
			Thread.sleep(1000); 
			GetVerify(bean.getActivityId(),bean.getIncludeProducts());				
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P3.class})
	@TestCase
	public void Tc_GetActivityInfo_006() {
		Logger.start(false,"获取直播详情-带商品-状态是未生效");
		try {
			int lid=LiveCallService.createLiveNotInEffect(sellerName,sellerId).getJSONObject("Data").getInt("ActivityId");
			LiveCallService.CreateLivesProductByLivesId(sellerId,sellerName,lid);
			Thread.sleep(1000); 
			bean.setActivityId(lid);
			bean.setIncludeProducts(true);
			call.setData(bean);
			call.callService();	
			GetVerify(bean.getActivityId(),bean.getIncludeProducts());	
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category({P3.class})
	@TestCase
	public void Tc_GetActivityInfo_007() {
		Logger.start(false,"获取买手主页直播详情-不带商品-直播id不存在");
		try { 
			bean.setActivityId(99999);
			bean.setIncludeProducts(false);
			call.setData(bean);
			call.callService();	
			Logger.verifyEquals(200, call.getCode(), "判断code是否为200");
			Logger.verifyEquals("操作成功",call.getMsg(), "判断Msg返回操作成功");
			Logger.verifyEquals(0,call.getBCode(), "判断操作成功时 业务代码是否0");
			Logger.verifyNotNull(call.getServerTime(), "判断服务器时间是否为空");
			Logger.verifyIsNull(call.getDataIsNull(), "判断Data为空");
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	private void GetVerify(Integer lid,Boolean includeProducts) throws Exception
	{
		LivesWapper wapper=new LivesWapper();
		if(lid!=0)
       {
            Map<String,Object> lst=wapper.getLivesBylid(lid);
			Logger.verifyEquals(200, call.getCode(), "判断code是否为200");
			Logger.verifyEquals("操作成功",call.getMsg(), "判断Msg返回操作成功");
			Logger.verifyEquals(0,call.getBCode(), "判断操作成功时 业务代码是否0");
			Logger.verifyNotNull(call.getServerTime(), "判断服务器时间是否为空");
			Logger.verifyEquals(lst.get("title"), call.getData().getString("Title"), "验证直播title是否与mongodb一致");
			Logger.verifyEquals(lst.get("vcover"), call.getData().getString("VideoCover"), "验证直播VideoCover是否与mongodb一致");
			Logger.verifyEquals(lst.get("vurl"), call.getData().getString("VideoUrl"), "验证直播VideoUrl是否与mongodb一致");
			Logger.verifyEquals(lst.get("action").toString(), call.getData().getString("Action").toString(), "验证直播Action是否与mongodb一致");
			Logger.verifyEquals(lst.get("lid").toString(), call.getData().getString("ActivityId").toString(), "验证直播ActivityId是否与mongodb一致");
			Logger.verifyEquals(lst.get("name"), call.getData().getString("ActivityName"), "验证直播ActivityName是否与mongodb一致");
			Logger.verifyEquals(lst.get("pic"), call.getData().getString("ActivityPicture"), "验证直播ActivityPicture是否与mongodb一致");

			Logger.verifyEquals((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(lst.get("add")).toString(), call.getData().getString("AddTime").toString(), "验证直播AddTime是否与mongodb一致");
			Logger.verifyEquals(lst.get("country"), call.getData().getString("Country"), "验证直播Country是否与mongodb一致");
			Logger.verifyEquals((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(lst.get("end")), call.getData().getString("EndTime"), "验证直播EndTime是否与mongodb一致");
			Logger.verifyEquals(lst.get("sid").toString(), call.getData().getString("SellerId").toString(), "验证直播SellerId是否与mongodb一致");
			Logger.verifyEquals(lst.get("addr"), call.getData().getString("ShopAddress"), "验证直播ShopAddress是否与mongodb一致");
			Logger.verifyEquals((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(lst.get("start")), call.getData().getString("StartTime"), "验证直播StartTime是否与mongodb一致");
			Logger.verifyEquals(lst.get("content"), call.getData().getString("ActivityInfo"), "验证直播ActivityInfo是否与mongodb一致");
			String start=(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(lst.get("start"));
			String end=(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(lst.get("end"));
			Logger.verifyEquals(GetActivityStatusText(lst,start,end), call.getData().getString("ActivityStatusText"), "验证直播ActivityStatusText是否与mongodb一致");
			Logger.verifyEquals(lst.get("cover")==null?"null":lst.get("cover").toString(), call.getData().getString("LiveCover"), "验证直播LiveCover是否与mongodb一致");
			
			Getbrand(wapper,lid,includeProducts);
		 }
	}
	private String GetActivityStatusText(Map<String,Object> lst,String start1,String end1) throws ParseException, JSONException
	{
		String text="";
		Date currentTime = new Date();

		if((int)lst.get("action")==1 )
		{
			Calendar calendar  =  new   GregorianCalendar(); 
			calendar.setTime(currentTime); 
			calendar.add(calendar.HOUR,1);
			Date newCurrentTime=calendar.getTime();
			
			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date start=format.parse(start1);
			Date end=format.parse(end1);
			if((boolean)lst.get("confirm")==true && ((currentTime.after(start)|| currentTime==start)&& (end.after(currentTime)|| currentTime==end)))
				text="直播中";
			else if((boolean)lst.get("confirm")==true && start.after(currentTime) && end.after(start))
				text="即将开始";
			else if((boolean)lst.get("confirm")==false && end.after(newCurrentTime))
				text="未生效";
			else
				text="已结束";
		}
		return text;
	}

	//1：根据直播活动Id（lid） 获取商品品牌，（LiveProducts）
	//2:根据商品id（spid）获取商品信息信息（Products）
	private void Getbrand(LivesWapper wapper,int livesId,Boolean includeProducts) throws Exception
	{
		LiveProductsWapper liveProductWapper=new LiveProductsWapper();
		ProductsWapper productWapper=new ProductsWapper();
		String spid="";
		//1
		ArrayList<String> lst=liveProductWapper.getLiveProductsBylid(livesId);
		for(int i=0;i<lst.size();i++)
		{
			JSONObject jo = new JSONObject(lst.get(i));
			spid=jo.getString("spid");
			//品牌
		}
		//2
		if(spid!="" && includeProducts==true)
		{
			ArrayList<String> plst=productWapper.getProductsBySpid(spid);
		 if(plst.size()>0 && call.GetProductList()!=null && call.GetProductList().length()>0)
		 {
			for(int j=0;j<plst.size();j++)
			{
			JSONObject pjo = new JSONObject(plst.get(j));

			Logger.verifyEquals(pjo.getBoolean("ispsp"), call.GetProductList().getJSONObject(j).getBoolean("IsPsp"), "验证直播商品IsPsp是否与mongodb一致");
			Logger.verifyEquals(pjo.getString("spid"), call.GetProductList().getJSONObject(j).getString("ProductId"), "验证直播商品ProductId是否与mongodb一致");
			Logger.verifyEquals(pjo.getJSONArray("pics").get(0), call.GetProductList().getJSONObject(j).getString("PicUrl"), "验证直播商品PicUrl是否与mongodb一致");
			//获取最低价格
			String[] mlst=pjo.getString("minp").split(",");
			
			List<BigDecimal> newmlst = new ArrayList();
			for(int k=0;k<mlst.length;k++)
			{
				 DecimalFormat df = new DecimalFormat("#.0");
				 BigDecimal m=new BigDecimal(mlst[k]);
				// BigDecimal m=new BigDecimal(df.format(mlst[k]));
				if(m.compareTo(new BigDecimal("0.0"))!=0)
					newmlst.add(m);
			}
			Collections.sort(newmlst);
			Logger.verifyEquals(newmlst.get(0).toString(), call.GetProductList().getJSONObject(j).getString("Price"), "验证直播商品Price是否与mongodb一致");
			Logger.verifyEquals(newmlst.get(0).toString(), call.GetProductList().getJSONObject(j).getString("VipPrice"), "验证直播商品VipPrice是否与mongodb一致");
			Logger.verifyEquals(newmlst.get(0).toString(), call.GetProductList().getJSONObject(j).getString("NewGuestPrice"), "验证直播商品NewGuestPrice是否与mongodb一致");
			//LiveProducts 上的 status
			ArrayList<String> lplst=liveProductWapper.getLivesProductsBySpid(spid);
			if(lplst.size()>0)
			{
				Logger.verifyEquals(new JSONObject(lplst.get(0)).getString("status"), call.GetProductList().getJSONObject(j).getString("SellStatus"), "验证直播商品SellStatus是否与mongodb一致");
			}
		   }
		}
		 else if(plst.size()>0 && (call.GetProductList()!=null || call.GetProductList().length()>0))
		 {
			 Logger.verifyNotNull(null, "验证直播商品集合GetProductList是否与mongodb一致");
		 }
		}
	}
}
